package com.tangqiao;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

public class ProcessCaller {
	public static final String cmd = "e:\\chess\\11xqcyclone\\cyclone.exe";
	public static String getNextStep(String chessBoard) {
		Process process;
		try {
			process = Runtime.getRuntime().exec(cmd);
			InputStream fis = process.getInputStream();
			OutputStream ous = process.getOutputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(fis));
			String line = null;
			ous.write("ucci\r\n".getBytes());
			ous.flush();
			while ((line = br.readLine()) != null) {
				// System.out.println(line);
				if (line.indexOf("ucciok") != -1) break;
			}
			ous.write(chessBoard.getBytes());
			ous.write(StepBanner.getInstance().getBanString(chessBoard).getBytes());
			ous.write("\r\ngo depth 8\r\n".getBytes());
			ous.flush();
			while ((line = br.readLine()) != null) {
				// System.out.println(line);
				if (line.indexOf("bestmove") != -1) break;
			}
			process.destroy();
			String [] args = line.split(" ");
			if (args.length > 1) return args[1];
			else return null;
		} catch (IOException e) {
			e.printStackTrace();
		} 
		return null;
	}
	public static void main(String[] args) {
		String chess = "position fen rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/4C2C1/9/RNBAKABNR w - - 0 1";
		String next = ProcessCaller.getNextStep(chess);
		System.out.println(next);
	}
}
